package com.zwps.biz.domain.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.ContentType;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zwps.biz.dal.redis.cache.AuthCache;
import com.zwps.biz.domain.service.CasService;
import com.zwps.biz.domain.tool.JwtTool;
import com.zwps.common.cache.CacheService;
import com.zwps.common.core.exception.UserActionException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class CasServiceImpl implements CasService {

    @Value("${application.cas.serviceOne}")
    private String serviceOne;
    @Value("${application.cas.serviceTwo}")
    private String serviceTwo;

    @Value("${application.auth.big-data-name}")
    private String authBigDataName;

    @Value("${application.auth.big-data-host}")
    private String authBigDataHost;

    @Value("${application.auth.big-data-time}")
    private long authBigDataTime;

    @Value("${application.auth.big-data-pwd}")
    private String authBigDataPwd;

    @Autowired
    private AuthCache authCache;

    private int timeout = 20000;
    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private CacheService cacheService;
    public JSONObject getUserByToken(String cToken) {
        String uri = "/systemapi/bus/api/getUserByToken";
        HttpRequest request = HttpUtil.createGet(serviceTwo + uri)
                .header("accept", ContentType.JSON.getValue())
                .timeout(timeout)
                .body("{" +
                        "\"cToken\":\"" + cToken + "\"," +
                        "\"systemCode\":\"jcfx\"" +
                        "}");
        try(HttpResponse response =  request.execute()) {
            log.info("{} 请求返回 {}", uri, response.body());
            JSONObject jsonObject = JSONObject.parseObject(response.body());
            String userId = (String) jsonObject.get("userid");
            if(StrUtil.isNotBlank(userId)) {
                cacheService.setValue(cToken, response.body(), 1000 * 60 * 180);
            }
            String tokenId = JwtTool.generateId(userId);
            String bigDataToken = acquireBigDataToken(tokenId);
            jsonObject.put("bigDataToken", bigDataToken);
            return jsonObject;
        } catch (Exception error) {
            throw new UserActionException("查询失败" + uri +  error.getMessage());
        }
    }

    public String validateToken(String cToken) {
        String uri = "/sltCas/validateToken";
        HttpRequest request = HttpUtil.createPost(serviceOne + uri)
                .header("accept", ContentType.JSON.getValue())
                .timeout(timeout)
                .body("{" +
                        "\"cToken\":\"" + cToken + "\"," +
                        "}");
        try(HttpResponse response =  request.execute()) {
            log.info("{} 请求返回 {}", uri, response.body());
            return response.body();
        } catch (Exception error) {
            throw new UserActionException("查询失败" + uri +  error.getMessage());
        }
    };

    public void login(String ticket, String cToken) {
        cacheService.setValue(ticket, cToken);
    }

    public String acquireBigDataToken(String token) {
        HttpRequest request = HttpUtil
                .createPost(authBigDataHost + "/system/auth/login/password");
        request.timeout(10000);
        request.body("{\"username\": \"" + authBigDataName + "\",\"password\": \"" + authBigDataPwd + "\"}");
        try (HttpResponse response = request.execute()) {
            if (response.getStatus() != 200) {
                throw new UserActionException("获取大数据Token失败，响应状态码：" + response.getStatus());
            }
            String dataJson = response.body();
            if (StrUtil.isBlank(dataJson)) {
                throw new UserActionException("大数据Token信息为空");
            }

            JSONObject jsonObject = JSON.parseObject(dataJson);
            int code = (int) jsonObject.get("code");
            if (code != 5000) {
                throw new UserActionException("获取大数据Token异常" + jsonObject.get("message"));
            }
            JSONObject jsonObject1 = (JSONObject) jsonObject.get("data");
            String bigDataToken = (String) jsonObject1.get("token");
            // 一个持有大数据token，一个记录刷新时间
            authCache.setToken(token + "_big_data_token", bigDataToken, authBigDataTime);
            return bigDataToken;
        } catch (Exception e) {
            e.printStackTrace();
            throw new UserActionException("获取大数据Token异常");
        }
    }
}
